package com.hujie.sqlqueryes.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.JsonData;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hujie.sqlqueryes.service.ElasticsearchConnectionManager;
import com.hujie.sqlqueryes.service.UserContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DSL执行服务实现类
 */
@Service
public class DslExecutionServiceImpl {
    
    private static final Logger logger = LoggerFactory.getLogger(DslExecutionServiceImpl.class);
    
    @Autowired
    private ElasticsearchConnectionManager connectionManager;
    
    private ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 根据DSL操作类型执行相应的Elasticsearch操作
     * @param dsl DSL字符串
     * @return 执行结果
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> executeDslOperation(String dsl) throws IOException {
        try {
            logger.info("开始执行DSL操作: {}", dsl);
            Map<String, Object> dslMap = objectMapper.readValue(dsl, Map.class);
            
            // 判断操作类型
            String operation = (String) dslMap.get("operation");
            logger.debug("操作类型: {}", operation);
            
            if (operation == null) {
                // 默认为查询操作
                logger.info("执行搜索操作");
                return executeSearch(dslMap);
            } else {
                switch (operation) {
                    case "insert":
                        logger.info("执行插入操作");
                        return executeInsert(dslMap);
                    case "update":
                        logger.info("执行更新操作");
                        Map<String, Object> updateResult = executeUpdate(dslMap);
                        // 如果是批量更新操作，需要实际执行
                        if ("update_by_query".equals(updateResult.get("operation"))) {
                            return executeUpdateByQuery(updateResult);
                        }
                        return updateResult;
                    case "delete":
                        logger.info("执行删除操作");
                        Map<String, Object> deleteResult = executeDelete(dslMap);
                        // 如果是批量删除操作，需要实际执行
                        if ("delete_by_query".equals(deleteResult.get("operation"))) {
                            return executeDeleteByQuery(deleteResult);
                        }
                        return deleteResult;
                    default:
                        logger.warn("不支持的操作类型: {}", operation);
                        throw new IOException("不支持的操作类型: " + operation);
                }
            }
        } catch (Exception e) {
            logger.error("执行DSL操作失败: {}", e.getMessage(), e);
            throw new IOException("执行DSL操作失败: " + e.getMessage());
        }
    }

    /**
     * 执行原生DSL查询（直接执行用户输入的DSL）
     * @param dsl DSL字符串
     * @return 查询结果
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> executeRawDslQuery(String dsl) throws IOException {
        try {
            logger.info("开始执行原生DSL查询: {}", dsl);
            Map<String, Object> dslMap = objectMapper.readValue(dsl, Map.class);

            // 检查是否包含index字段
            Object indexObj = dslMap.get("index");
            String index = null;
            if (indexObj instanceof String) {
                index = (String) indexObj;
            } else if (indexObj instanceof List) {
                List<String> indices = (List<String>) indexObj;
                if (!indices.isEmpty()) {
                    index = indices.get(0);
                }
            }

            // 处理索引名称
            String processedIndexName = processIndexName(index);
            logger.debug("处理后的索引名称: {}", processedIndexName);

            // 构建搜索请求
            SearchRequest.Builder searchBuilder = new SearchRequest.Builder()
                    .index(processedIndexName != null ? processedIndexName : "_all");

            // 设置查询条件
            if (dslMap.containsKey("query")) {
                Map<String, Object> query = (Map<String, Object>) dslMap.get("query");
                co.elastic.clients.elasticsearch._types.query_dsl.Query queryObj = convertMapToQueryBuilder(query);
                searchBuilder.query(queryObj);
            } else {
                // 无查询条件时使用match_all
                searchBuilder.query(q -> q.matchAll(m -> m));
            }

            // 处理其他可能的参数（size、from、sort）保持不变
            if (dslMap.containsKey("size")) {
                searchBuilder.size(((Number) dslMap.get("size")).intValue());
            }

            if (dslMap.containsKey("from")) {
                searchBuilder.from(((Number) dslMap.get("from")).intValue());
            }

            if (dslMap.containsKey("sort")) {
                Object sortObj = dslMap.get("sort");
                if (sortObj instanceof List) {
                    List<Map<String, Object>> sortList = (List<Map<String, Object>>) sortObj;
                    for (Map<String, Object> sortItem : sortList) {
                        for (Map.Entry<String, Object> entry : sortItem.entrySet()) {
                            String field = entry.getKey();
                            Object value = entry.getValue();
                            if (value instanceof Map) {
                                Map<String, Object> sortParams = (Map<String, Object>) value;
                                String orderStr = (String) sortParams.get("order");
                                co.elastic.clients.elasticsearch._types.SortOrder order =
                                        orderStr != null ? co.elastic.clients.elasticsearch._types.SortOrder.valueOf(orderStr.toUpperCase())
                                                : co.elastic.clients.elasticsearch._types.SortOrder.Asc;
                                searchBuilder.sort(s -> s.field(f -> f.field(field).order(order)));
                            }
                        }
                    }
                }
            }

            SearchRequest searchRequest = searchBuilder.build();
            logger.debug("构建的搜索请求: {}", searchRequest);

            // 执行搜索
            // 使用ThreadLocal中的用户ID获取客户端
            ElasticsearchClient client = connectionManager.getCurrentClient();
            if (client == null) {
                throw new IOException("Elasticsearch client not connected for current user");
            }
            
            SearchResponse<Map> searchResponse = client.search(searchRequest, Map.class);
            logger.info("搜索完成，耗时: {}ms，命中: {}条记录", searchResponse.took(), searchResponse.hits().total().value());

            // 构建返回结果（保持不变）
            Map<String, Object> result = new HashMap<>();
            result.put("took", searchResponse.took());
            result.put("timed_out", searchResponse.timedOut());
            result.put("total", searchResponse.hits().total().value());
            result.put("success", true);

            List<Map<String, Object>> hits = new ArrayList<>();
            for (Hit<Map> hit : searchResponse.hits().hits()) {
                Map<String, Object> hitData = new HashMap<>();
                hitData.put("id", hit.id());
                hitData.put("source", hit.source());
                hitData.put("score", hit.score());
                hits.add(hitData);
            }

            result.put("hits", hits);
            result.put("dsl", dslMap);

            return result;
        } catch (Exception e) {
            logger.error("执行原生DSL查询失败: {}", e.getMessage(), e);
            throw new IOException("执行原生DSL查询失败: " + e.getMessage());
        }
    }

    /**
     * 将Map转换为Query对象
     */
    @SuppressWarnings("unchecked")
    private co.elastic.clients.elasticsearch._types.query_dsl.Query convertMapToQueryBuilder(Map<String, Object> queryMap) {
        if (queryMap == null || queryMap.isEmpty()) {
            return new co.elastic.clients.elasticsearch._types.query_dsl.Query.Builder()
                    .matchAll(m -> m)
                    .build();
        }

        try {
            String queryType = queryMap.keySet().iterator().next();
            Map<String, Object> queryDetails = (Map<String, Object>) queryMap.get(queryType);

            switch (queryType) {
                case "term":
                    String termFieldName = queryDetails.keySet().iterator().next();
                    Object termFieldValue = queryDetails.get(termFieldName);
                    // term查询使用FieldValue
                    return new co.elastic.clients.elasticsearch._types.query_dsl.Query.Builder()
                            .term(t -> t.field(termFieldName).value(convertToFieldValue(termFieldValue)))
                            .build();

                case "range":
                    String rangeFieldName = queryDetails.keySet().iterator().next();
                    Map<String, Object> rangeValues = (Map<String, Object>) queryDetails.get(rangeFieldName);
                    co.elastic.clients.elasticsearch._types.query_dsl.RangeQuery.Builder rangeBuilder =
                            new co.elastic.clients.elasticsearch._types.query_dsl.RangeQuery.Builder()
                                    .field(rangeFieldName);

                    // range查询使用JsonData
                    if (rangeValues.containsKey("gte")) {
                        rangeBuilder.gte(convertToJsonData(rangeValues.get("gte")));
                    }
                    if (rangeValues.containsKey("gt")) {
                        rangeBuilder.gt(convertToJsonData(rangeValues.get("gt")));
                    }
                    if (rangeValues.containsKey("lte")) {
                        rangeBuilder.lte(convertToJsonData(rangeValues.get("lte")));
                    }
                    if (rangeValues.containsKey("lt")) {
                        rangeBuilder.lt(convertToJsonData(rangeValues.get("lt")));
                    }

                    return new co.elastic.clients.elasticsearch._types.query_dsl.Query.Builder()
                            .range(rangeBuilder.build())
                            .build();

                // 其他查询类型（match/match_all）保持不变
                case "match":
                    String matchFieldName = queryDetails.keySet().iterator().next();
                    Object matchFieldValue = queryDetails.get(matchFieldName);
                    return new co.elastic.clients.elasticsearch._types.query_dsl.Query.Builder()
                            .match(m -> m.field(matchFieldName).query(String.valueOf(matchFieldValue)))
                            .build();

                case "match_all":
                    return new co.elastic.clients.elasticsearch._types.query_dsl.Query.Builder()
                            .matchAll(m -> m)
                            .build();

                default:
                    logger.warn("不支持的查询类型: {}, 使用match_all查询", queryType);
                    return new co.elastic.clients.elasticsearch._types.query_dsl.Query.Builder()
                            .matchAll(m -> m)
                            .build();
            }
        } catch (Exception e) {
            logger.error("查询条件转换失败: {}", e.getMessage(), e);
            return new co.elastic.clients.elasticsearch._types.query_dsl.Query.Builder()
                    .matchAll(m -> m)
                    .build();
        }
    }

    /**
     * 转换为FieldValue（用于term查询）
     */
    private FieldValue convertToFieldValue(Object value) {
        if (value == null) {
            return FieldValue.of((String) null);
        }
        if (value instanceof String) {
            return FieldValue.of((String) value);
        }
        if (value instanceof Number) {
            Number num = (Number) value;
            return num instanceof Integer || num instanceof Long
                    ? FieldValue.of(num.longValue())
                    : FieldValue.of(num.doubleValue());
        }
        if (value instanceof Boolean) {
            return FieldValue.of((Boolean) value);
        }
        // 复杂类型转为字符串
        return FieldValue.of(value.toString());
    }

    /**
     * 转换为JsonData（用于range查询）
     */
    private JsonData convertToJsonData(Object value) {
        if (value == null) {
            return JsonData.of(null); // 处理null
        }
        if (value instanceof String) {
            return JsonData.of((String) value);
        }
        if (value instanceof Number) {
            return JsonData.of((Number) value);
        }
        if (value instanceof Boolean) {
            return JsonData.of((Boolean) value);
        }
        // 复杂类型（Map/List）通过Jackson转换为JsonNode
        try {
            return JsonData.of(objectMapper.valueToTree(value));
        } catch (Exception e) {
            logger.warn("转换为JsonData失败，使用字符串: {}", value, e);
            return JsonData.of(value.toString());
        }
    }

    /**
     * 执行搜索操作
     * @param dslMap DSL映射
     * @return 搜索结果
     */
    private Map<String, Object> executeSearch(Map<String, Object> dslMap) throws IOException {
        String index = (String) dslMap.get("index");
        Map<String, Object> query = (Map<String, Object>) dslMap.get("query");
        
        // 处理包含特殊字符的索引名称
        String processedIndexName = processIndexName(index);
        logger.debug("处理后的索引名称: {}", processedIndexName);
        
        // 获取客户端
        ElasticsearchClient client = connectionManager.getCurrentClient();
        if (client == null) {
            throw new IOException("Elasticsearch client not connected for current user");
        }
        
        // 构建搜索请求
        SearchRequest.Builder searchBuilder = new SearchRequest.Builder()
                .index(processedIndexName);
        
        // 设置查询条件
        if (query != null) {
            // 根据DSL构建真正的查询
            try {
                // 获取查询类型（例如: term, match等）
                String queryType = query.keySet().iterator().next();
                Map<String, Object> queryDetails = (Map<String, Object>) query.get(queryType);
                
                switch (queryType) {
                    case "term":
                        String fieldName = queryDetails.keySet().iterator().next();
                        Object fieldValue = queryDetails.get(fieldName);
                        searchBuilder.query(q -> q.term(t -> t.field(fieldName).value(String.valueOf(fieldValue))));
                        break;
                    case "match":
                        String matchFieldName = queryDetails.keySet().iterator().next();
                        Object matchFieldValue = queryDetails.get(matchFieldName);
                        searchBuilder.query(q -> q.match(m -> m.field(matchFieldName).query(String.valueOf(matchFieldValue))));
                        break;
                    case "match_all":
                        searchBuilder.query(q -> q.matchAll(m -> m));
                        break;
                    default:
                        logger.warn("不支持的查询类型: {}, 使用match_all查询", queryType);
                        searchBuilder.query(q -> q.matchAll(m -> m));
                        break;
                }
            } catch (Exception e) {
                logger.error("查询条件转换失败，使用match_all查询", e);
                searchBuilder.query(q -> q.matchAll(m -> m));
            }
        } else {
            searchBuilder.query(q -> q.matchAll(m -> m));
        }
        
        // 处理分页参数
        if (dslMap.containsKey("size")) {
            searchBuilder.size(((Number) dslMap.get("size")).intValue());
        }
        
        if (dslMap.containsKey("from")) {
            searchBuilder.from(((Number) dslMap.get("from")).intValue());
        }
        
        SearchRequest searchRequest = searchBuilder.build();
        logger.debug("构建的搜索请求: {}", searchRequest);
        
        // 执行搜索
        SearchResponse<Map> searchResponse = client.search(searchRequest, Map.class);
        logger.info("搜索完成，耗时: {}ms，命中: {}条记录", searchResponse.took(), searchResponse.hits().total().value());
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("took", searchResponse.took());
        result.put("timed_out", searchResponse.timedOut());
        result.put("total", searchResponse.hits().total().value());
        
        List<Map<String, Object>> hits = new ArrayList<>();
        for (Hit<Map> hit : searchResponse.hits().hits()) {
            Map<String, Object> hitData = new HashMap<>();
            hitData.put("id", hit.id());
            hitData.put("source", hit.source());
            hitData.put("score", hit.score());
            hits.add(hitData);
        }
        
        result.put("hits", hits);
        result.put("dsl", dslMap);
        
        return result;
    }
    
    /**
     * 执行插入操作
     * @param dslMap DSL映射
     * @return 插入结果
     */
    private Map<String, Object> executeInsert(Map<String, Object> dslMap) throws IOException {
        String index = (String) dslMap.get("index");
        
        // 处理包含特殊字符的索引名称
        String processedIndexName = processIndexName(index);
        logger.debug("处理后的索引名称: {}", processedIndexName);
        
        // 获取客户端
        ElasticsearchClient client = connectionManager.getCurrentClient();
        if (client == null) {
            throw new IOException("Elasticsearch client not connected for current user");
        }
        
        // 检查是否有多个文档要插入
        if (dslMap.containsKey("docs")) {
            // 处理多个文档插入
            List<Map<String, Object>> docs = (List<Map<String, Object>>) dslMap.get("docs");
            logger.info("批量插入 {} 个文档到索引: {}", docs.size(), processedIndexName);
            
            // 构建批量请求
            List<co.elastic.clients.elasticsearch.core.bulk.BulkOperation> operations = new ArrayList<>();
            for (Map<String, Object> doc : docs) {
                co.elastic.clients.elasticsearch.core.bulk.BulkOperation operation = 
                    new co.elastic.clients.elasticsearch.core.bulk.BulkOperation.Builder()
                        .index(i -> i
                            .index(processedIndexName)
                            .document(doc))
                        .build();
                operations.add(operation);
            }
            
            // 执行批量插入
            co.elastic.clients.elasticsearch.core.BulkRequest bulkRequest = 
                co.elastic.clients.elasticsearch.core.BulkRequest.of(b -> b
                    .operations(operations));
            
            co.elastic.clients.elasticsearch.core.BulkResponse bulkResponse = client.bulk(bulkRequest);
            logger.info("批量插入完成，成功: {}，失败: {}", 
                bulkResponse.items().stream().filter(item -> item.error() == null).count(),
                bulkResponse.items().stream().filter(item -> item.error() != null).count());
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("result", "bulk_insert");
            result.put("total", docs.size());
            result.put("success", bulkResponse.items().stream().filter(item -> item.error() == null).count());
            result.put("failed", bulkResponse.items().stream().filter(item -> item.error() != null).count());
            return result;
        } else {
            // 处理单个文档插入
            Map<String, Object> doc = (Map<String, Object>) dslMap.get("doc");
            
            // 构建索引请求
            IndexRequest<Map<String, Object>> indexRequest = IndexRequest.of(i -> i
                    .index(processedIndexName)
                    .document(doc)
            );
            logger.debug("构建的索引请求: {}", indexRequest);
            
            // 执行索引操作
            IndexResponse response = client.index(indexRequest);
            logger.info("文档插入完成，ID: {}，结果: {}", response.id(), response.result().jsonValue());
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("result", response.result().jsonValue());
            result.put("id", response.id());
            result.put("version", response.version());
            return result;
        }
    }
    
    /**
     * 执行更新操作
     * @param dslMap DSL映射
     * @return 更新结果
     */
    private Map<String, Object> executeUpdate(Map<String, Object> dslMap) throws IOException {
        String index = (String) dslMap.get("index");
        Map<String, Object> doc = (Map<String, Object>) dslMap.get("doc");
        Map<String, Object> query = (Map<String, Object>) dslMap.get("query");
        
        // 处理包含特殊字符的索引名称
        String processedIndexName = processIndexName(index);
        logger.debug("处理后的索引名称: {}", processedIndexName);
        
        // 获取客户端
        ElasticsearchClient client = connectionManager.getCurrentClient();
        if (client == null) {
            throw new IOException("Elasticsearch client not connected for current user");
        }
        
        // 检查是否是通过ID更新
        if (query != null && query.containsKey("ids")) {
            // 通过ID更新
            Map<String, Object> idsQuery = (Map<String, Object>) query.get("ids");
            List<String> values = (List<String>) idsQuery.get("values");
            if (values != null && !values.isEmpty()) {
                String docId = values.get(0); // 取第一个ID
                
                // 构建更新请求
                UpdateRequest<Map, Map> updateRequest = UpdateRequest.of(u -> u
                        .index(processedIndexName)
                        .id(docId)
                        .doc(doc)
                );
                logger.debug("构建的更新请求: {}", updateRequest);
                
                // 执行更新操作
                UpdateResponse<Map> response = client.update(updateRequest, Map.class);
                logger.info("文档更新完成，ID: {}，结果: {}", response.id(), response.result().jsonValue());
                
                // 构建返回结果
                Map<String, Object> result = new HashMap<>();
                result.put("result", response.result().jsonValue());
                result.put("id", response.id());
                result.put("version", response.version());
                return result;
            }
        }
        
        // 使用_update_by_query进行批量更新
        StringBuilder scriptSource = new StringBuilder();
        List<String> scriptParams = new ArrayList<>();
        for (Map.Entry<String, Object> entry : doc.entrySet()) {
            if (scriptSource.length() > 0) {
                scriptSource.append("; ");
            }
            scriptSource.append("ctx._source.").append(entry.getKey()).append(" = params.param").append(scriptParams.size());
            scriptParams.add(String.valueOf(entry.getValue()));
        }
        
        // 构建_update_by_query请求
        Map<String, Object> result = new HashMap<>();
        result.put("operation", "update_by_query");
        result.put("index", processedIndexName);
        result.put("script", scriptSource.toString());
        result.put("params", scriptParams);
        result.put("query", query);
        
        logger.info("准备执行批量更新操作");
        logger.debug("更新脚本: {}", scriptSource);
        logger.debug("查询条件: {}", query);
        
        return result;
    }
    
    /**
     * 执行_update_by_query操作
     * @param params 参数
     * @return 执行结果
     */
    @SuppressWarnings("unchecked")
    private Map<String, Object> executeUpdateByQuery(Map<String, Object> params) throws IOException {
        String index = (String) params.get("index");
        String scriptSource = (String) params.get("script");
        List<String> scriptParams = (List<String>) params.get("params");
        Map<String, Object> query = (Map<String, Object>) params.get("query");
        
        logger.info("执行批量更新操作，索引: {}", index);
        
        // 获取客户端
        ElasticsearchClient client = connectionManager.getCurrentClient();
        if (client == null) {
            throw new IOException("Elasticsearch client not connected for current user");
        }
        
        // 构建脚本参数
        Map<String, co.elastic.clients.json.JsonData> scriptParamsMap = new HashMap<>();
        for (int i = 0; i < scriptParams.size(); i++) {
            scriptParamsMap.put("param" + i, co.elastic.clients.json.JsonData.of(scriptParams.get(i)));
        }
        
        // 构建请求
        co.elastic.clients.elasticsearch.core.UpdateByQueryRequest request = 
            co.elastic.clients.elasticsearch.core.UpdateByQueryRequest.of(builder -> builder
                .index(index)
                .script(s -> s.inline(i -> i.source(scriptSource).params(scriptParamsMap)))
                .query(q -> {
                    // 根据查询类型构建查询对象
                    try {
                        String queryType = query.keySet().iterator().next();
                        Map<String, Object> queryDetails = (Map<String, Object>) query.get(queryType);
                        
                        switch (queryType) {
                            case "term":
                                String fieldName = queryDetails.keySet().iterator().next();
                                Object fieldValue = queryDetails.get(fieldName);
                                return q.term(t -> t.field(fieldName).value(String.valueOf(fieldValue)));
                            case "match":
                                String matchFieldName = queryDetails.keySet().iterator().next();
                                Object matchFieldValue = queryDetails.get(matchFieldName);
                                return q.match(m -> m.field(matchFieldName).query(String.valueOf(matchFieldValue)));
                            case "match_all":
                                return q.matchAll(m -> m);
                            default:
                                logger.warn("不支持的查询类型: {}, 使用match_all查询", queryType);
                                return q.matchAll(m -> m);
                        }
                    } catch (Exception e) {
                        logger.error("查询条件转换失败，使用match_all查询", e);
                        return q.matchAll(m -> m);
                    }
                }));
        
        // 执行更新
        co.elastic.clients.elasticsearch.core.UpdateByQueryResponse response = client.updateByQuery(request);
        
        logger.info("批量更新完成，更新文档数: {}", response.updated());
        
        Map<String, Object> result = new HashMap<>();
        result.put("result", "updated"); // 添加result字段以匹配测试期望
        result.put("updated", response.updated());
        result.put("version_conflicts", response.versionConflicts());
        return result;
    }
    
    /**
     * 执行删除操作
     * @param dslMap DSL映射
     * @return 删除结果
     */
    private Map<String, Object> executeDelete(Map<String, Object> dslMap) throws IOException {
        String index = (String) dslMap.get("index");
        Map<String, Object> query = (Map<String, Object>) dslMap.get("query");
        
        // 处理包含特殊字符的索引名称
        String processedIndexName = processIndexName(index);
        logger.debug("处理后的索引名称: {}", processedIndexName);
        
        // 获取客户端
        ElasticsearchClient client = connectionManager.getCurrentClient();
        if (client == null) {
            throw new IOException("Elasticsearch client not connected for current user");
        }
        
        // 检查是否是通过ID删除
        if (query != null && query.containsKey("ids")) {
            // 通过ID删除
            Map<String, Object> idsQuery = (Map<String, Object>) query.get("ids");
            List<String> values = (List<String>) idsQuery.get("values");
            if (values != null && !values.isEmpty()) {
                String docId = values.get(0); // 取第一个ID
                
                // 构建删除请求
                DeleteRequest deleteRequest = DeleteRequest.of(d -> d
                        .index(processedIndexName)
                        .id(docId)
                );
                logger.debug("构建的删除请求: {}", deleteRequest);
                
                // 执行删除操作
                DeleteResponse response = client.delete(deleteRequest);
                logger.info("文档删除完成，ID: {}，结果: {}", response.id(), response.result().jsonValue());
                
                // 构建返回结果
                Map<String, Object> result = new HashMap<>();
                result.put("result", response.result().jsonValue());
                result.put("id", response.id());
                return result;
            }
        }
        
        // 使用delete_by_query进行批量删除
        Map<String, Object> result = new HashMap<>();
        result.put("operation", "delete_by_query");
        result.put("index", processedIndexName);
        result.put("query", query);
        
        logger.info("准备执行批量删除操作");
        logger.debug("查询条件: {}", query);
        
        return result;
    }
    
    /**
     * 执行delete_by_query操作
     * @param params 参数
     * @return 执行结果
     */
    @SuppressWarnings("unchecked")
    private Map<String, Object> executeDeleteByQuery(Map<String, Object> params) throws IOException {
        String index = (String) params.get("index");
        Map<String, Object> query = (Map<String, Object>) params.get("query");
        
        logger.info("执行批量删除操作，索引: {}", index);
        
        // 获取客户端
        ElasticsearchClient client = connectionManager.getCurrentClient();
        if (client == null) {
            throw new IOException("Elasticsearch client not connected for current user");
        }
        
        // 构建请求
        co.elastic.clients.elasticsearch.core.DeleteByQueryRequest request = 
            co.elastic.clients.elasticsearch.core.DeleteByQueryRequest.of(builder -> builder
                .index(index)
                .query(q -> {
                    // 根据查询类型构建查询对象
                    try {
                        String queryType = query.keySet().iterator().next();
                        Map<String, Object> queryDetails = (Map<String, Object>) query.get(queryType);
                        
                        switch (queryType) {
                            case "term":
                                String fieldName = queryDetails.keySet().iterator().next();
                                Object fieldValue = queryDetails.get(fieldName);
                                return q.term(t -> t.field(fieldName).value(String.valueOf(fieldValue)));
                            case "match":
                                String matchFieldName = queryDetails.keySet().iterator().next();
                                Object matchFieldValue = queryDetails.get(matchFieldName);
                                return q.match(m -> m.field(matchFieldName).query(String.valueOf(matchFieldValue)));
                            case "match_all":
                                return q.matchAll(m -> m);
                            default:
                                logger.warn("不支持的查询类型: {}, 使用match_all查询", queryType);
                                return q.matchAll(m -> m);
                        }
                    } catch (Exception e) {
                        logger.error("查询条件转换失败，使用match_all查询", e);
                        return q.matchAll(m -> m);
                    }
                }));
        
        // 执行删除
        co.elastic.clients.elasticsearch.core.DeleteByQueryResponse response = client.deleteByQuery(request);
        
        logger.info("批量删除完成，删除文档数: {}", response.deleted());
        
        Map<String, Object> result = new HashMap<>();
        result.put("result", "deleted"); // 添加result字段以匹配测试期望
        result.put("deleted", response.deleted());
        return result;
    }
    
    /**
     * 处理索引名称，如果包含特殊字符（如连字符）则去除方括号
     * @param indexName 原始索引名称
     * @return 处理后的索引名称
     */
    private String processIndexName(String indexName) {
        // 检查索引名称是否被方括号包装
        if (indexName != null && indexName.startsWith("[") && indexName.endsWith("]")) {
            // 去除方括号
            return indexName.substring(1, indexName.length() - 1);
        }
        return indexName;
    }
}